package cn.wxManage.user.service.impl;

import cn.common.common.model.ServerResponse;
import cn.common.user.model.BaseUserAddress;
import cn.wxManage.common.model.DistrictInfo;
import cn.wxManage.user.dao.UserAddressMapper;
import cn.wxManage.user.model.UserAddress;
import cn.wxManage.user.model.UserInfo;
import cn.wxManage.user.service.IAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Zhang on 2019/1/31.
 */
@Service
public class AddressService implements IAddressService{
    @Autowired
    HttpServletRequest request;

    @Autowired
    UserAddressMapper userAddressMapper;

    @Override
    public ServerResponse<?> handleUserAddress(UserAddress userAddress) {
        UserInfo userInfo = getUserInfo();
        if (userAddress.getId() == null){
            if (userAddress.getDefaultAddress() == null){
                userAddress.setDefaultAddress(0);
            }
            userAddress.setUserid(userInfo.getUserid());
            userAddressMapper.insertSelective(userAddress);
        }else {
            userAddress.setDefaultAddress(null);
            userAddress.setUserid(null);
            userAddressMapper.updateByPrimaryKeySelective(userAddress);
        }
        return ServerResponse.createBySuccessMessage("操作成功");
    }

    @Override
    public ServerResponse<?> deleteUserAddress(Integer id) {
        userAddressMapper.deleteByPrimaryKey(id);
        return ServerResponse.createBySuccessMessage("删除成功");
    }

    @Override
    public ServerResponse<?> setDefaultAddress(Integer id) {
        BaseUserAddress userAddress = userAddressMapper.selectByPrimaryKey(id);
        userAddressMapper.initNotDefault(userAddress.getUserid());
        userAddress.setDefaultAddress(1);
        userAddressMapper.updateByPrimaryKeySelective(userAddress);
        return ServerResponse.createBySuccessMessage("操作成功");
    }

    @Override
    public ServerResponse<?> getUserAddress() {
        List<UserAddress> userAddressList = userAddressMapper.getUserAddress(getUserInfo().getUserid());
        return ServerResponse.createBySuccess(userAddressList);
    }

    @Override
    public ServerResponse<?> getAddressList(String fatherAdCode) {
        if (fatherAdCode == null || "".equals(fatherAdCode)){
            fatherAdCode = "100000";
        }
        List<DistrictInfo> districtInfoList = userAddressMapper.getAddressList(fatherAdCode);
        return ServerResponse.createBySuccess(districtInfoList);
    }

    private UserInfo getUserInfo(){
        return (UserInfo) request.getAttribute("userInfo");
    }
}
